home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Aminet 52
/
Aminet 52 (2002)(GTI - Schatztruhe)[!][Dec 2002].iso
/
Aminet
/
text
/
misc
/
thai-conv.lha
/
thaiconv.cc
< prev
next >
Wrap
C/C++ Source or Header
|
2002-09-24
|
3KB
|
116 lines
/**
* @file thaiconv.cc
* @brief Convert from UTF-8 to TIS-620 coded text
* author Lyndon Hill (koan)
* last edit 11.09.02 Catching invalid UTF8
* 03.09.02 Added reverse direction for coding
* 09.08.02 First working version
* note: build with > g++ thaiconv.cc -o thaiconv -lm
*
* (c) 2002. Permission given to aminet for distribution
*/
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
int main(int argc, char *argv[])
{
int a, bitval;
if((argc < 2) || (argc > 3))
{
cout << "Usage: thaiconv in-file [convert file to TIS-620]\n";
cout << " thaiconv in-file utf8 [convert file to UTF-8]\n";
exit(0);
}
char *infile = argv[1];
bool tis620 = true;
if(argc == 3) tis620 = false;
// open file
ifstream myinput(infile);
if(myinput.bad())
{
cout << "Could not open '" << infile << "'\n";
exit(0);
}
// read data
unsigned char temp;
unsigned char temp2;
unsigned char temp3;
int total;
// stop at end of file
while(temp = myinput.get())
{
if(myinput.eof())
break;
// convert coding
if((int)(temp) > 127)
{
if(tis620 == true)
{
if((temp >= 0xc0) && (temp <= 0xfd))
{
// valid utf 8
// deal with multibyte coding
temp2 = myinput.get(); // second byte, should check for error
if((temp != 224) && ((temp2 < 184) || (temp2 > 187))) break; // not Thai
temp3 = myinput.get(); // here too
temp -= 224; temp *= 16384;
temp2 -= 128; temp2 *= 64;
temp3 -= 128;
total = temp+temp2+temp3;
total = total - 0xe00 + 0xa0; // convert UTF -> TIS
cout << (unsigned char)(total); // output ascii equivalent
}
}
else
{
// convert to multibyte coding
total = (int)(temp) - 0xa0 + 0xe00; // convert TIS -> UTF
temp = 224; temp2 = 128; temp3 = 128;
for(a = 15; a >= 12; a--)
{
bitval = pow(2.0, a);
if(total >= bitval)
{
total -= bitval;
temp += pow(2.0, a-12);
}
}
for(a = 11; a >= 6; a--)
{
bitval = pow(2.0, a);
if(total >= bitval)
{
total -= bitval;
temp2 += pow(2.0, a-6);
}
}
for(a = 5; a >= 0; a--)
{
bitval = pow(2.0, a);
if(total >= bitval)
{
total -= bitval;
temp3 += pow(2.0, a);
}
}
cout << temp << temp2 << temp3;
}
}
else cout << temp; // standard 7 bit ascii
}
exit(1);
}